﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Core.Framework.Model.Common
{

    /// <summary>
    /// 注册服务商
    /// </summary>
    public class BuildServiceProvider
    {

        #region Parameter

        /// <summary>
        /// 服务盒子
        /// </summary>
        static IServiceCollection ServiceCollection { get; } = new ServiceCollection();

        /// <summary>
        /// 服务容器
        /// </summary>
        static IServiceProvider _Provider { get; set; }

        /// <summary>
        /// 局部锁
        /// </summary>
        static object ProviderLock { get; set; } = new object();

        /// <summary>
        /// 获取服务
        /// </summary>
        private static IServiceProvider _serviceProvider
        {
            get
            {
                if (_Provider == null)
                {
                    lock (ProviderLock)
                    {
                        if (_Provider == null)
                        {
                            _Provider = ServiceCollection
                                .BuildServiceProvider();
                        }
                    }

                }

                return _Provider;
            }
            set
            {
                _Provider = value;
            }
        }

        #endregion



        /// <summary>
        /// 初始化服务注册
        /// </summary>
        public static void DIRegister(IServiceCollection services)
        {
            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IDIRegister))))
                .ToArray();

            foreach (var aHandler in types)
            {
                var iRegister = (IDIRegister) Activator.CreateInstance(aHandler);

                iRegister.Execute(ServiceCollection);

                if (services != null)
                {
                    iRegister.Execute(services);
                }
            }
        }
        
        /// <summary>
        /// 获取服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static T GetService<T>() where T : class
        {
            var provider = _serviceProvider.GetService<T>();

            return provider;
        }

        /// <summary>
        /// 添加服务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public static void RegService(Action<IServiceCollection> action)
        {
            if (action != null)
            {
                action.Invoke(ServiceCollection);
                _Provider = null;
            }
        }

    }
}
